// 主程序入口
import { computeNetworkCharacteristics } from './network_characteristics.js';
import { clusterEdges, extractSkeleton, computeBindings, warpEdges } from './sbeb.js';
import { buildEdges, buildCompatibilityLists, runFDEB } from './fdeb.js';
import { drawClusteredEdges, drawSkeletons, drawWarpedEdges, drawFDEBEdges, toggleBtnContent, setupUI} from './ui.js';

import { config } from './config.js';
import { loadCsvData } from './util.js';

let nodes = [], edges = [];
let clustered = new Map();
let skeletons = {};
let bindings = {};
let warped = [];
let fdebEdges = [];
let viewer;

Cesium.Ion.defaultAccessToken = config.defaultAccessToken;
async function initCesium() {
  viewer = new Cesium.Viewer("cesiumContainer",  {
    shouldAnimate: true,
  });

  // 自动加载数据和预计算
  ({ nodes, edges } = await loadCsvData(config.nodes_csv, config.edges_csv));
  showNetworkCharacteristics(nodes, edges);
  clustered = clusterEdges(edges, nodes, config.cluseredK, config.kmeansMaxIterations);
  skeletons = extractSkeleton(clustered, nodes, config.maxSkeletonSegmentLength);
  bindings = computeBindings(nodes, skeletons, clustered);
  warped = warpEdges(bindings, nodes, config.warpSegments, config.warpAlpha);

  fdebEdges = buildEdges(edges, nodes, config.initialSubdivisionPoints);
  console.log("Built compatibilities");
  buildCompatibilityLists(fdebEdges, config.compatibilityThreshold);

  console.log("✅ 所有数据已预处理完毕");
}

const shownEntities = new Map(); // key: 'cluster', 'skeleton', 'warped'

setupUI({
    onCluster: () => {
        const key = 'cluster';
        const btn = document.getElementById('btn-cluster');
        if (shownEntities.has(key)) {
          shownEntities.get(key).forEach(e => viewer.entities.remove(e));
          shownEntities.delete(key);
          toggleBtnContent(btn);
        } else {
          const entities = drawClusteredEdges(clustered, nodes, viewer);
          shownEntities.set(key, entities);
          toggleBtnContent(btn);
        }
    },
    onSkeleton: () => {
        const key = 'skeleton';
        const btn = document.getElementById('btn-skeleton');
        if (shownEntities.has(key)) {
          shownEntities.get(key).forEach(e => viewer.entities.remove(e));
          shownEntities.delete(key);
          toggleBtnContent(btn);
        } else {
          const entities = drawSkeletons(skeletons, viewer);;
          shownEntities.set(key, entities);
          toggleBtnContent(btn);
        }
    },
    onWarp: () => {
        const key = 'warped';
        const btn = document.getElementById('btn-warp');
        if (shownEntities.has(key)) {
          shownEntities.get(key).forEach(e => viewer.entities.remove(e));
          shownEntities.delete(key);
          toggleBtnContent(btn);
        } else {
          const entities = drawWarpedEdges(warped, bindings, viewer);
          shownEntities.set(key, entities);
          toggleBtnContent(btn);
        }
    },
    onRunFDEB: () => {
      runFDEB(fdebEdges, {
        K: config.fdebPhases, 
        C: config.iterationsPerPhase, 
        P: config.initialSubdivisionPoints, 
        S: config.forceStepSize});
      console.log(fdebEdges);
      console.log("run fdeb done.");
      const key = "fdeb";
      const btn = document.getElementById('btn-fdeb');
      if (shownEntities.has(key)) {
        shownEntities.get(key).forEach(e => viewer.entities.remove(e));
        shownEntities.delete(key);
      }
      btn.textContent = btn.textContent.replace('隐藏', '显示');
    },
    onFDEB: () => {
      console.log("onToggleFDEB");
      // TODO keys to constants 
      const key = "fdeb";
      const btn = document.getElementById('btn-fdeb');
      if (shownEntities.has(key)) {
        shownEntities.get(key).forEach(e => viewer.entities.remove(e));
        shownEntities.delete(key);
        toggleBtnContent(btn);
      } else {
        const entities = drawFDEBEdges(fdebEdges, viewer);
        shownEntities.set(key, entities);
        toggleBtnContent(btn);
      }
    },
    onReset: () => {
      viewer.entities.removeAll();      // 清空图形
      shownEntities.clear();            // 清除状态标记
      for (const key of ['btn-cluster', 'btn-skeleton', 'btn-warp', 'btn-fdeb']) {
        console.log("key ... ");
        console.log(key);
        const btn = document.getElementById(key);
        btn.textContent = btn.textContent.replace('隐藏', '显示');
      }
      console.log("🔄 图形已清除，数据保留");
    },
});

function showNetworkCharacteristics(nodes, edges) {
  const {
    nodeCount,
    edgeCount,
    averageDegree,
    averageBetweenness,
  } = computeNetworkCharacteristics(nodes, edges);

  document.getElementById('value-nodes').textContent = nodeCount;
  document.getElementById('value-edges').textContent = edgeCount;
  document.getElementById('value-degree').textContent = averageDegree.toFixed(2);
  document.getElementById('value-betweenness').textContent = averageBetweenness.toFixed(2);
}

initCesium();